package cn.calm.swing.osgi.file.New.tracker;

import java.util.List;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import cn.calm.swing.osgi.api.DefaultServiceTracker;
import cn.calm.swing.osgi.api.WizardItemService;

public class WizardItemServiceTracker extends
		DefaultServiceTracker<WizardItemService, WizardItemService> {
	private DefaultMutableTreeNode root;
	private JTree tree;

	public WizardItemServiceTracker(BundleContext context,
			DefaultMutableTreeNode root, JTree tree) {
		super(context, WizardItemService.class, null);
		this.root = root;
		this.tree = tree;
	}


	@Override
	protected void processShape(int action,
			ServiceReference<WizardItemService> reference,
			WizardItemService service) {
		
		switch (action) {
		case MODIFIED:
			DefaultMutableTreeNode parent = null;
			if (service.getParent() == null) {
				parent = root;
			} else {
				parent = service.getParent().getNode();
			}
			parent.remove(service.getNode());
		case ADDED:
			processAdd(reference, service,WizardItemService.WIZARD_ITEM_TREE,WizardItemService.class);
			break;
		case REMOVED:
			DefaultMutableTreeNode parent1 = null;
			if (service.getParent() == null) {
				parent1 = root;
			} else {
				parent1 = service.getParent().getNode();
			}
			parent1.remove(service.getNode());
			break;
		}
		tree.updateUI();
	}

	@Override
	protected void prepreParent(WizardItemService parent) {
		parent.getNode().removeAllChildren();
	}

	@Override
	protected void processParent(WizardItemService service,
			WizardItemService parent) {
		DefaultMutableTreeNode parent1 = null;
		if (service.getParent() == null) {
			parent1 = root;
		} else {
			service.setParent(parent);
			parent1 = service.getParent().getNode();
		}
		parent1.add(service.getNode());
	}

	@Override
	protected void sortService(List<ServiceReference<WizardItemService>> list) {
	}

}
